package tt.dz.order.service.rpc.client;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;

import org.apache.avro.Protocol;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.ipc.NettyTransceiver;
import org.apache.avro.ipc.generic.GenericRequestor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import tt.dz.order.vo.WhiteListInfo;

/**
 * @Title: 订单系统调用OMS提供的RPC服务封装的客户端类
 * @author zhoutian   
 * @date 2015-11-17
 */
@Component
public class OmsRpcClient {
	private static Logger log = LoggerFactory.getLogger(OmsRpcClient.class);
	
	@Value(value="${rpc.oms.ip}")
	private String ip;
	
	@Value(value="${rpc.oms.port}")
	private int port;
	
	private Protocol protocol;

	public OmsRpcClient() {}

    @PostConstruct
	public void init(){
    	try {
			String filePath = this.getClass().getResource("omsAvro.json").getPath();
			protocol = Protocol.parse(new File(filePath));
		} catch (IOException e) {
			log.error("初始化OmsRpcClient出错", e);
		}
    }
    
    public WhiteListInfo getWhiteListInfo(String userId, String serviceProviderCode){
    	NettyTransceiver transceiver = null;
		try {
			transceiver = new NettyTransceiver(new InetSocketAddress(ip, port));
			GenericRequestor requestor = new GenericRequestor(protocol, transceiver);
			GenericRecord requestData = new GenericData.Record(protocol.getMessages().get("getWhiteListInfo").getRequest());  
			requestData.put("userId", userId);
			requestData.put("serviceProviderCode", serviceProviderCode);
	        Object result = requestor.request("getWhiteListInfo", requestData);
	        if (result instanceof String) {
	        	WhiteListInfo whiteListInfo = JSON.parseObject(result.toString(), WhiteListInfo.class);
	        	return whiteListInfo;
	        }
		} catch (Exception e) {
			log.error("调用OMS提供的白名单方法出错", e);
		} finally {
			if(transceiver != null) transceiver.close();
		}
    	return null;
    }
}
